package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.domain.Goods;
import cn.wolfcode.trip.base.domain.TravelCommend;
import cn.wolfcode.trip.base.query.GoodsQueryObject;
import cn.wolfcode.trip.base.service.IGoodsService;
import cn.wolfcode.trip.base.service.IGoodsTypeService;
import cn.wolfcode.trip.base.util.JasonResult;
import cn.wolfcode.trip.base.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

/**
 * 商品资源控制器
 *
 * @author Lyu
 */
@Controller
@RequestMapping("/goods")
public class GoodsController {

    private final IGoodsService goodsService;
    private final IGoodsTypeService goodsTypeService;

    @Autowired
    public GoodsController(IGoodsService goodsService, IGoodsTypeService goodsTypeService) {
        this.goodsService = goodsService;
        this.goodsTypeService = goodsTypeService;
    }

    /**
     * 分类查询商品列表
     *
     * @param model x
     * @param qo    x
     * @return x
     */
    @RequestMapping("/list")
    public Object list(Model model, @ModelAttribute("qo") GoodsQueryObject qo) {
        qo.setPageSize(5);
        model.addAttribute("pageInfo", goodsService.queryForList(qo));
        model.addAttribute("types", goodsTypeService.listAll());
        return "/goods/list";
    }

    /**
     * 新增商品或修改
     * 新增完之后就跳到主页面
     */
    @RequestMapping("/saveOrUpdate")
    public Object saveOrUpdate(Goods goods, MultipartFile img) {
        //判断一下文件有没有上传过来
        if (img != null && img.getContentType().startsWith("image") && img.getSize() > 0) {
            //如果有上传图片的文件过来的话就将原来的封面替换掉
            String url = UploadUtil.upload(img);
            goods.setCoverUrl(url);
        }
        //执行新增或者修改的语句
        goodsService.saveOrUpdate(goods);
        return "redirect:/goods/list.do";
    }

    /**
     * 下架商品
     */
    @RequestMapping("/delete")
    public Object delete(Long id) {
        goodsService.delete(id);
        return new JasonResult();
    }
}
